'''
Created on 14/04/2009

@author: eh01
'''
from yarra.datastore import dsconstants, dsofactory
from yarra.datastore.dsstub import DSStub
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager
from yarra.logindecorator import adminLoginRequired
import httplib
import os


class HTTPRequestGETNodeLastConnected(BaseEventHandler):

    @adminLoginRequired
    def do(self, data):
        dso = data
        ds_stub = DSStub()
        nodes = ds_stub.get_nodes()
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()                    
        event_type = eventconstants.HTTP_RESPONSE_EVENT_TYPE
        # get the path of the appropriate html template
        relative_path = "../../../pages/hub/node-last-connected.html"
        
        # get the html
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        data_html = ""
        for node_id in nodes.keys():
            data_html += "<tr><td>" + str(node_id) + "</td><td>" + str(nodes[node_id]) + "</td></tr>"            
        html_string = html_template_string.replace('${data}', data_html)
        # create new dso        
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)            
        event = Event(event_type, new_dso)
        EventManager().add_event(event)